<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>全选练习</title>
  </head>
  <body>
    你爱好的运动是？
    <br />
    <input type="checkbox" name="item" />足球 <input type="checkbox" name="item" />篮球 <input type="checkbox" name="item" />羽毛球
    <input type="checkbox" name="item" />乒乓球
    <br />
    <button id="checkAll">全选</button>
    <button id="checkNone">全不选</button>
    <button id="checkInvert">反选</button>
    <button id="submit">提交</button>

    <script>
      var items = document.getElementsByName("item");

      function onClick(idStr, callback) {
        var element = document.getElementById(idStr);
        element.onclick = callback;
      }

      // 全选
      onClick("checkAll", function () {
        items.forEach(ele => {
          ele.checked = true;
        });
      });

      // 全不选
      onClick("checkNone", function () {
        items.forEach(ele => {
          ele.checked = false;
        });
      });

      // 反选
      onClick("checkInvert", function () {
        items.forEach(ele => {
          var checked = ele.checked;
          ele.checked = !checked;
        });
      });

      // 提交
      onClick("submit", function () {
        items.forEach(ele => {
          var checked = ele.checked;
          if (checked) {
            alert(ele.nextSibling.nodeValue);
          }
        });
      });
    </script>
  </body>
</html>
